<?php

namespace App\Jobs\QiPao\Draw;

use App\Enums\AppJumpEnum;
use App\Exceptions\BasicException;
use App\Jobs\Job;
use App\Repositories\GiftRepository;
use App\Repositories\Pet\PetPropsRepository;
use App\Services\Draw\DrawConst\CacheKey;
use App\Services\Draw\Enum\DrawEnum;
use App\Services\Tools\PushService;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PetDrawStatisticsJob extends Job
{
    protected $statisticsData;
    protected $poolGroup;
    protected $user;
    protected $cachePrefix;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($poolGroup, $user, $statisticsData, $cachePrefix)
    {
        $this->statisticsData = $statisticsData;
        $this->poolGroup      = $poolGroup;
        $this->user           = $user;
        $this->cachePrefix    = $cachePrefix;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $date  = date('Ymd');
        $week  = date('YW');
        $month = date('Ym');
        $year  = date('Y');
        try {
            Log::info('奖池统计：' );
            $redisObject = app('redis')->connection('game');
            $poolConfig  = app('model_lottery_pet_pool_config')->info();
            //$this->staticsSeasonData($poolConfig, $redisObject);
            //数据统计
            $userId = $this->user->user_id;
            $redisObject->setbit($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_DATE . "_" . $date, $userId, 1);
            $redisObject->setbit($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_WEEK . "_" . $week, $userId, 1);
            $redisObject->setbit($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_MONTH . "_" . $month, $userId, 1);
            $redisObject->setbit($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_YEAR . "_" . $year, $userId, 1);


            //数据统计
            $dateStatistics             = app('model_lottery_pet_statistics')->firstOrCreate(['time' => $date, 'type' => 1], ['time' => $date, 'type' => 1]);
            $weekStatistics             = app('model_lottery_pet_statistics')->firstOrCreate(['time' => $week, 'type' => 2], ['time' => $date, 'type' => 1]);
            $monthStatistics            = app('model_lottery_pet_statistics')->firstOrCreate(['time' => $month, 'type' => 3], ['time' => $date, 'type' => 1]);
            $yearStatistics             = app('model_lottery_pet_statistics')->firstOrCreate(['time' => $year, 'type' => 4], ['time' => $date, 'type' => 1]);
            $dateStatistics->input      += $this->statisticsData['input'];
            $dateStatistics->output     += $this->statisticsData['output'];
            $dateStatistics->count      += $this->statisticsData['count'];
            $dateStatistics->user_count = $redisObject->bitcount($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_DATE . "_" . $date);
            $dateStatistics->save();

            $weekStatistics->input      += $this->statisticsData['input'];
            $weekStatistics->output     += $this->statisticsData['output'];
            $weekStatistics->count      += $this->statisticsData['count'];
            $weekStatistics->user_count = $redisObject->bitcount($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_WEEK . "_" . $week);

            $weekStatistics->save();

            $monthStatistics->input      += $this->statisticsData['input'];
            $monthStatistics->output     += $this->statisticsData['output'];
            $monthStatistics->count      += $this->statisticsData['count'];
            $monthStatistics->user_count = $redisObject->bitcount($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_MONTH . "_" . $month);
            $monthStatistics->save();

            $yearStatistics->input      += $this->statisticsData['input'];
            $yearStatistics->output     += $this->statisticsData['output'];
            $yearStatistics->count      += $this->statisticsData['count'];
            $yearStatistics->user_count = $redisObject->bitcount($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_YEAR . "_" . $year);
            $yearStatistics->save();

            //统计道具赛季数据

        } catch (\Exception $e) {
            Log::error('萌宠抽奖统计错误：' . $e->getMessage());
        }

    }
//
//    public function staticsSeasonData($poolConfig, $redisObject)
//    {
//        try {
//            //累计赛季值
//            $gifts         = $this->statisticsData['gift_list'];
//            $prop          = $gifts->where('type', DrawEnum::PROP_GIFT_TYPE)->first();
//            $propGiftCount = $gifts->where('type', DrawEnum::PROP_GIFT_TYPE)->sum('count');
//            if ($propGiftCount <= 0) {
//                return null;
//            }
//            //赛季值达到
//            $isSendSeasonGift    = false;
//            $seasonOriginSeq     = 20220730000001;
//            $nextSeasonPropCount = 0;
//            $seasonSeq           = $redisObject->get($this->cachePrefix . "seasonSeq") ?? 0;
//            $luckyValue          = 0;
//            if ($redisObject->set($this->cachePrefix . "luckyDrawLock", 1, 'ex', 5, 'nx')) {
//                if (($luckyValue = $redisObject->incrby($this->cachePrefix . "seasonValue", $propGiftCount)) >= $poolConfig['lucky_count']) {
//                    //进入下个赛季
//                    $seasonSeq = $redisObject->incrby($this->cachePrefix . "seasonSeq", 1);
//                    //幸运值清零
//                    $nextSeasonPropCount = $redisObject->incrby($this->cachePrefix . "seasonValue", -$poolConfig['lucky_count']);
//                    $luckyValue          = $luckyValue - $poolConfig['lucky_count'];
//                    $isSendSeasonGift    = true;
//                    app('events')->listen('draw.redisJobRollback', function () use ($propGiftCount, $poolConfig, $redisObject) {
//                        $redisObject->incrby($this->cachePrefix . "seasonValue", $poolConfig['lucky_count'] - $propGiftCount);
//                    });
//                } else {
//                    $redisObject->del($this->cachePrefix . "luckyDrawLock");
//                    app('events')->listen('draw.redisJobRollback', function () use ($propGiftCount, $poolConfig, $redisObject) {
//                        $redisObject->incrby($this->cachePrefix . "seasonValue", -$propGiftCount);
//                    });
//                }
//            } else {
//                $luckyValue = $redisObject->incrby($this->cachePrefix . "seasonValue", $propGiftCount);
//                app('events')->listen('draw.redisJobRollback', function () use ($propGiftCount, $poolConfig, $redisObject) {
//                    $redisObject->incrby($this->cachePrefix . "seasonValue", -$propGiftCount);
//                });
//            }
//
//            (new PushService())->petLuckyValuePush($luckyValue > $poolConfig->lucky_count ? ($luckyValue - $poolConfig->lucky_count) : $luckyValue, $poolConfig->lucky_count);
//
//            $season = $seasonOriginSeq + $seasonSeq;
//            //统计用户赛季道具信息
//            $seasonAddPropGiftCount = $propGiftCount;
//            $userSeasonRecord       = app('model_lottery_pet_user_season_record')->firstOrCreate([
//                "user_id" => $this->user->user_id,
//                "season"  => $season,
//            ]);
//            if ($isSendSeasonGift) {
//                //更新上一季的道具值
//                $lastSeason             = app('model_lottery_pet_user_season_record')->firstOrCreate([
//                    "user_id" => $this->user->user_id,
//                    "season"  => $season - 1,
//                ]);
//                $lastSeason->draw_count += $this->statisticsData['count'];
//                $lastSeason->prop_count += $propGiftCount - $nextSeasonPropCount;
//                $lastSeason->save();
//                $seasonAddPropGiftCount = $nextSeasonPropCount;
//            } else {
//                $userSeasonRecord             = app('model_lottery_pet_user_season_record')->firstOrCreate([
//                    "user_id" => $this->user->user_id,
//                    "season"  => $season,
//                ]);
//                $userSeasonRecord->draw_count += $this->statisticsData['count'];
//            }
//            if ($seasonAddPropGiftCount > 0) {
//                if (empty($userSeasonRecord)) {
//                    $userSeasonRecord       = app('model_lottery_pet_user_season_record')->firstOrCreate([
//                        "user_id" => $this->user->user_id,
//                        "season"  => $season,
//                    ]);
//                }
//                $userSeasonRecord->prop_count += $seasonAddPropGiftCount;
//                $userSeasonRecord->save();
//            }
//
//            //统计赛季道具
//            if ($isSendSeasonGift || $seasonSeq == 0) {
//                //新赛季
//                $seasonStatistics = app('model_lottery_pet_season_statistics')->firstOrCreate(['season' => $season]);
//            }
//
//            $redisObject->setbit($this->cachePrefix . "season:userStatistics" . "_" . $season, $this->user->user_id, 1);
//            $userCount = $redisObject->bitcount($this->cachePrefix . "season:userStatistics" . "_" . $season);
//            if ($isSendSeasonGift) {
//                //更新上一季的道具值
//                $lastSeasonUserCount = $redisObject->bitcount($this->cachePrefix . "season:userStatistics" . "_" . ($season - 1));
//                app('model_lottery_pet_season_statistics')->updateData(['season' => $season - 1], ['user_count' => $lastSeasonUserCount,
//                                                                                                   'prop_count' => DB::raw('prop_count+' . ($propGiftCount - $nextSeasonPropCount))]);
//            }
//            app('model_lottery_pet_season_statistics')->updateData(['season' => $season], ['user_count' => $userCount,
//                                                                                           'prop_count' => DB::raw('prop_count+' . $seasonAddPropGiftCount)]);
//            //排行榜道具发放
//            if ($isSendSeasonGift) {
//                $this->settleLastSeason($season, $prop);
//            }
//        } catch (\Exception $e) {
//            //触发redis回滚事务
//            app('events')->fire('draw.redisJobRollback');
//            file_put_contents(storage_path() . '/logs/season' . date('Ymd') . '.log',
//                '赛季错误' . $e->getMessage(). PHP_EOL, FILE_APPEND
//            );
//            Log::error('赛季道具发送异常' . $e->getMessage());
//        }
//
//    }
//
//    public function settleLastSeason($season, $props)
//    {
//
//        //查询上个赛季排行榜用户
//        $lastSeason     = app('model_lottery_pet_season_statistics')->one([['season', '<', $season], 'present_prop_count' => 0]);
//        $seasonRankList = app('model_lottery_pet_user_season_record')->list(['season' => $lastSeason['season']], ['user_id', 'prop_count'], 'prop_count');
//        if (empty($seasonRankList)) {
//            Log::info('未找到上赛季数据' . $season);
//            return null;
//        }
//        $seasonPresentPropCount = 0;
//        $presentPropGiftData    = [];
//        $presentPropCount       = 0;
//        foreach ($seasonRankList as $key => $data) {
//            $rank = $key + 1;
//            if ($key >= 3) {
//                $presentPropGiftData[]  = [
//                    'id'                 => $props->id,
//                    'user_id'            => $data['user_id'],
//                    'present_prop_count' => 20,
//                    'count'              => 20
//                ];
//                $seasonPresentPropCount += 20;
//                $prizeMessage           = "共计奖励20张金闪卡";
//            } else {
//                $presentPropGiftData[]  = [
//                    'id'                 => $props->id,
//                    'user_id'            => $data['user_id'],
//                    'present_prop_count' => $data['prop_count'] * (3 - $key),
//                    'count'              => $data['prop_count'] * (3 - $key)
//                ];
//                $seasonPresentPropCount += $data['prop_count'] * (3 - $key);
//                $presentPropCount       = $data['prop_count'] * (3 - $key);
//                switch ($key) {
//                    case 0:
//                        $prizeMessage = "闪金卡数量额外三倍，共计奖励{$presentPropCount}张金闪卡";
//                        break;
//                    case 1:
//                        $prizeMessage = "闪金卡数量额外二倍，共计奖励{$presentPropCount}张金闪卡";
//                        break;
//                    case 2:
//                        $prizeMessage = "闪金卡数量额外一倍，共计奖励{$presentPropCount}张金闪卡";
//                        break;
//                }
//            }
//
//            app('model_user_news')->sendUserNews($data['user_id'], '活动通知',
//                "恭喜您在【萌兽盲盒】第【{$lastSeason->season}】赛季中获得第{$rank}名，{$prizeMessage}，请前往【绿洲集市】进行查看，祝心愿达成！",
//                0, 0, 0, AppJumpEnum::SYSTEM_MESSAGE_SOURCE);
//
//
//        }
//        DB::connection('mysql_game')->beginTransaction();
//        try {
//            //统计赛季赠送道具
//            app('model_lottery_pet_season_statistics')->updateData(['season' => $lastSeason['season']], ['season_end_time' => Carbon::now(), 'present_prop_count' => $seasonPresentPropCount]);
//            //统计赛季用户赠送道具
//            app('model_lottery_pet_user_season_record')->batchUpdatePresentProps($lastSeason['season'], $presentPropGiftData);
//            //发送道具到用户背包
//            PetPropsRepository::getInstance()->batchAddUserProps($presentPropGiftData);
//            DB::connection('mysql_game')->commit();
//        } catch (\Exception $e) {
//            DB::connection('mysql_game')->rollBack();
//            throw $e;
//        }
//    }

    /* public function fail($exception = null )
     {
         Log::error('giftJob:'.$exception->getMessage());
     }*/
}
